<template>
  <main-container style="width: 400px; margin: 50px auto">
    <h1>jaguar 授权平台</h1>
    <br />
    <el-divider />
    <h3>{{ data.clientId }}</h3>
    <br />
    <div>申请获取你的信息</div>
    <el-form
      ref="dataForm"
      label-suffix="："
      label-width="160px"
      method="post"
      action="/api/jaguar-auth-server/oauth/authorize"
    >
      <div v-show="false">
        <el-input name="user_oauth_approval" v-model="user_oauth_approval" />
        <el-input name="client_id" v-model="client_id" />
        <el-input name="redirect_uri" v-model="redirect_uri" />
        <el-input name="response_type" v-model="response_type" />
        <el-input name="state" v-model="state" />
      </div>
      <br />

      <el-form-item v-for="(value, key) in data.scopes" :key="key" :label="key">
        <el-switch
          :ref="'scope.' + key"
          :name="'scope.' + key"
          v-model="data.scopes[key]"
          :active-value="true"
          :inactive-value="false"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
      </el-form-item>

      <el-button type="primary" @click="submitHandler">授权</el-button>
    </el-form>
    <br />
  </main-container>
</template>
<script>
import { authorize } from '@/api/oauth2'
import MainContainer from '@/components/MainContainer'

export default {
  name: 'OAuth2Authorize',
  props: {
    client_id: {
      type: String,
      required: true,
    },
    redirect_uri: {
      type: String,
      required: true,
    },
    state: {
      type: String,
    },
  },
  data() {
    return {
      data: {},
      user_oauth_approval: 'true',
      response_type: 'code',
    }
  },
  components: {
    MainContainer,
  },
  mounted() {
    this.listScopes()
  },
  methods: {
    listScopes() {
      authorize({
        client_id: this.client_id,
        redirect_uri: this.redirect_uri,
        response_type: this.response_type,
      }).then((res) => {
        let data = res.data.data
        data.scopes = {}
        for (let scope in data.scope) {
          data.scopes[data.scope[scope]] = 'false'
        }
        this.data = data
      })
    },
    submitHandler() {
      for (let scope in this.data.scopes) {
        let input = this.$refs['scope.' + scope][0].input
        input.value = this.data.scopes[scope]
      }
      this.$refs.dataForm.$el.submit()
    },
  },
}
</script>
